package com.fifth.home.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fifth.common.pojo.dto.CommonResult;
import com.fifth.common.pojo.entity.Banner;
import com.fifth.home.service.IBannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.core.Local;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * @Package: com.wzh.config
 * @ClassName: QuartzTask
 * @Author: 王振华
 * @Description:
 * @Date: 2022/7/25 19:09
 * @Version: 1.0
 */
@Component  //该类交于spring容器来管理
public class QuartzTask {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IBannerService bannerService;

    //任务代码cron:定于定时任务的规则
    //   表示每日0点到1点 执行任务
    @Scheduled(cron = "0 0 0,1 * * ?")
    public void task01() {
        try {
            LocalDateTime time = LocalDateTime.now();

            List<JSONObject> banner = JSON.parseObject(redisTemplate.opsForValue().get("banner"), List.class);

            for (JSONObject item : banner) {
                String gmtModified = (String) item.get("gmtModified");
                String replace = gmtModified.replace("T", " ");
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                //把字符串转为日期格式
                LocalDateTime parse2 = LocalDateTime.parse(replace, dateTimeFormatter);

                Duration dt = Duration.between(time, parse2);
                //System.out.println(dt.toMinutes());

                if (dt.toMinutes() < 0) {
                    bannerService.updateStatus((String) item.get("id"), "1");

                    Boolean banner1 = redisTemplate.delete("banner");

                    //System.out.println(banner1);

                }
            }
        }catch (Exception e){

        }


    }
}